﻿
using CTP.CRM.Core.Redis;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using System.Reflection;
using System.Text;
using Volo.Abp.Application.Services;

namespace CTP.CRM.Core
{
    public class PublicTools
    {
        //
        // 摘要:
        //     根据条件过滤获取程序集
        //
        // 参数:
        //   assemblyWhere:
        public static IEnumerable<Assembly> GetAssembliesByFilter(Func<Assembly, bool>? assemblyWhere = null)
        {
            string[] filterAssemblies = new string[4] { "System.", "Microsoft.", "JeBrains.", "netstandard" };
            IEnumerable<AssemblyName> enumerable = from asm in DependencyContext.Default.GetDefaultAssemblyNames()
                                                   where asm.Name != null && !filterAssemblies.Any((string f) => asm.Name.StartsWith(f))
                                                   select asm;
            List<Assembly> list = new List<Assembly>();
            foreach (AssemblyName item in enumerable)
            {
                list.Add(Assembly.Load(item));
            }

            return (assemblyWhere == null) ? list : list.Where(assemblyWhere).ToList();
        }

        //
        // 摘要:
        //     判断当前类型是不是Action
        //
        // 参数:
        //   method:
        //
        //   ReflectedType:
        public static bool IsApiAction(MethodInfo method, Type ReflectedType)
        {
            if (!method.IsPublic || method.IsAbstract || method.IsStatic || method.IsGenericMethod)
            {
                return false;
            }

            if (method.ReflectedType != ReflectedType || method.DeclaringType == typeof(object))
            {
                return false;
            }

            if (method.IsDefined(typeof(ApiExplorerSettingsAttribute), inherit: true) && method.GetCustomAttribute<ApiExplorerSettingsAttribute>(inherit: true).IgnoreApi)
            {
                return false;
            }

            return true;
        }

        //
        // 摘要:
        //     判断当前类型是不是Controller
        //
        // 参数:
        //   type:
        public static bool IsApiController(Type type)
        {
            if (!type.IsPublic || type.IsPrimitive || type.IsValueType || type.IsAbstract || type.IsInterface || type.IsGenericType)
            {
                return false;
            }

            if ((!typeof(Controller).IsAssignableFrom(type) && typeof(ControllerBase).IsAssignableFrom(type)) || typeof(IApplicationService).IsAssignableFrom(type))
            {
                if (type.IsDefined(typeof(ApiExplorerSettingsAttribute), inherit: true) && type.GetCustomAttribute<ApiExplorerSettingsAttribute>(inherit: true).IgnoreApi)
                {
                    return false;
                }

                return true;
            }

            return false;
        }

        //
        // 摘要:
        //     生成流水号
        //
        // 参数:
        //   prefix:
        //     前缀
        //
        //   place:
        //     序列位位数
        //
        //   preConditions:
        //     流水号生成前置条件
        //
        //   dateTimeFormat:
        //     时间类型转换规则
        //
        //   expiration:
        //     过期时间（单位秒，默认 7776000 秒 约等于90天）如果想永不过期传-1
        //
        // 返回结果:
        //     新的流水号
        public static string GetSerialNumber(string prefix, int place, Func<bool> preConditions = null, string dateTimeFormat = "yyyyMMdd", int expiration = 7776000, string customerCode = "")
        {
            string text = (string.IsNullOrEmpty(customerCode) ? (prefix + DateTime.Now.ToString(dateTimeFormat)) : customerCode);
            string key = "SerialCode:" + text;
            if (!RedisHelper.Client.Exists(key))
            {
                RedisHelper.Client.Set(key, 0, expiration);
            }

            long num = 0L;
            if (preConditions == null)
            {
                num = RedisHelper.Client.IncrBy(key, 1L);
            }
            else
            {
                if (!preConditions())
                {
                    return "";
                }

                num = RedisHelper.Client.IncrBy(key, 1L);
            }

            return text + num.ToString().PadLeft(place, '0');
        }

        //
        // 摘要:
        //     生成指定位数的字母字符串
        //
        // 参数:
        //   length:
        public static string RndLetter(int length)
        {
            char[] array = new char[50]
            {
            'a', 'b', 'd', 'c', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'p', 'r', 'q', 's', 't', 'u',
            'v', 'w', 'z', 'y', 'x', 'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Q',
            'P', 'R', 'T', 'S', 'V', 'U', 'W', 'X', 'Y', 'Z'
            };
            StringBuilder stringBuilder = new StringBuilder();
            Random random = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < length; i++)
            {
                stringBuilder.Append(array[random.Next(0, array.Length)].ToString());
            }

            return stringBuilder.ToString();
        }
    }
}
